package com.zx.onlineeducation.service.cms.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.onlineeducation.common.util.R;
import com.zx.onlineeducation.service.cms.entity.BannerDO;
import com.zx.onlineeducation.service.cms.entity.vo.BannerQueryVO;
import com.zx.onlineeducation.service.cms.service.BannerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 轮播图 前端控制器
 * </p>
 *
 * @author 郑雪
 * @since 2022-01-23
 */
@Api(tags = "轮播图管理")
@RestController
@RequestMapping("/cms/banner")
@CrossOrigin // 解决跨域
public class BannerController {

    /**
     * 轮播图服务接口
     */
    @Autowired
    private BannerService bannerService;

    @ApiOperation("获取轮播图分页列表")
    @PostMapping("/page/{current}/{size}")
    public R page(
            @ApiParam(value = "当前页")
            @PathVariable("current") Long current,
            @ApiParam(value = "每页显示条数")
            @PathVariable("size") Long size,
            @ApiParam(value = "轮播图查询对象")
            @RequestBody BannerQueryVO bannerQueryVO) {
        if(size == null || size == 0) {
            size = 5L;
        }
        // 执行分页查询
        Page<BannerDO> page = bannerService.page(current, size, bannerQueryVO);
        // 获取总记录数
        long total = page.getTotal();
        // 获取数据列表
        List<BannerDO> records = page.getRecords();
        // 返回结果
        return R.ok().data("total", total).data("records", records);
    }

    @ApiOperation("添加轮播图")
    @PostMapping("/save")
    public R save(
            @ApiParam(value = "轮播图数据对象")
            @RequestBody BannerDO bannerDO) {
        boolean save = bannerService.saveBanner(bannerDO);
        return save ? R.ok() : R.error();
    }

    @ApiOperation("根据ID查询轮播图")
    @GetMapping("/{id}")
    public R getById(
            @ApiParam(value = "轮播图ID", required = true)
            @PathVariable("id") String id) {
        BannerDO bannerDO = bannerService.getById(id);
        return R.ok().data("banner", bannerDO);
    }

    @ApiOperation("修改轮播图")
    @PutMapping("/{id}")
    public R update(
            @ApiParam(value = "轮播图ID", required = true)
            @PathVariable("id") String id,
            @ApiParam(value = "轮播图数据对象")
            @RequestBody BannerDO bannerDO) {
        bannerDO.setId(id);
        boolean update = bannerService.updateBannerById(bannerDO);
        return update ? R.ok() : R.error();
    }

    @ApiOperation("逻辑删除轮播图")
    @DeleteMapping("/{id}")
    public R remove(
            @ApiParam(value = "轮播图ID", required = true)
            @PathVariable("id") String id) {
        boolean remove = bannerService.removeBannerById(id);
        return remove ? R.ok() : R.error();
    }

}

